package com.lmx.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmx.api.annotation.AuthCheck;
import com.lmx.api.common.BaseResponse;
import com.lmx.api.common.DeleteRequest;
import com.lmx.api.common.ErrorCode;
import com.lmx.api.common.ResultUtils;
import com.lmx.api.exception.BusinessException;
import com.lmx.api.model.dto.UserInterfanceInfo.UserInterfanceInfoAddRequest;
import com.lmx.api.model.dto.UserInterfanceInfo.UserInterfanceInfoQueryRequest;
import com.lmx.api.model.dto.UserInterfanceInfo.UserInterfanceInfoUpdateRequest;
import com.lmx.commen.model.entity.User;
import com.lmx.commen.model.entity.UserInterfanceInfo;
import com.lmx.api.service.UserInterfanceInfoService;
import com.lmx.api.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author lmx
 */
@RestController
@RequestMapping("/userinterfance")
public class UserInterfanceInfoController {
    @Resource
    private UserInterfanceInfoService userInterfanceInfoService;
    @Resource
    private UserService userService;

    /**
     * 创建
     *
     * @param userInterfanceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addPost(@RequestBody UserInterfanceInfoAddRequest userInterfanceInfoAddRequest, HttpServletRequest request) {
        if (userInterfanceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfanceInfo userInterfanceInfo = new UserInterfanceInfo();
        BeanUtils.copyProperties(userInterfanceInfoAddRequest, userInterfanceInfo);
        // 校验
        userInterfanceInfoService.validInterfanceInfo(userInterfanceInfo, true);
        User loginUser = userService.getLoginUser(request);
        userInterfanceInfo.setUserid(loginUser.getId());
        boolean result = userInterfanceInfoService.save(userInterfanceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newPostId = userInterfanceInfo.getId();
        return ResultUtils.success(newPostId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserInterfanceInfo oldUserInterfanceInfo = userInterfanceInfoService.getById(id);
        if (oldUserInterfanceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldUserInterfanceInfo.getUserid().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = userInterfanceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param userInterfanceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updatePost(@RequestBody UserInterfanceInfoUpdateRequest userInterfanceInfoUpdateRequest,
                                            HttpServletRequest request) {

        if (userInterfanceInfoUpdateRequest == null || userInterfanceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfanceInfo userInterfanceInfo = new UserInterfanceInfo();
        BeanUtils.copyProperties(userInterfanceInfoUpdateRequest, userInterfanceInfo);
        // 参数校验
        userInterfanceInfoService.validInterfanceInfo(userInterfanceInfo, false);
        User user = userService.getLoginUser(request); //得到当前登录的用户
        long id = userInterfanceInfo.getId();
        // 判断是否存在
        UserInterfanceInfo oldInterfanceInfo = userInterfanceInfoService.getById(id);
        if (oldInterfanceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfanceInfo.getUserid().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = userInterfanceInfoService.updateById(userInterfanceInfo);
        return ResultUtils.success(result);
    }


    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<UserInterfanceInfo> getPostById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        UserInterfanceInfo interfanceInfo = userInterfanceInfoService.getById(id);
        return ResultUtils.success(interfanceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfanceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/list")
    public BaseResponse<List<UserInterfanceInfo>> listPost(@RequestBody UserInterfanceInfoQueryRequest interfanceInfoQueryRequest) {
        UserInterfanceInfo interfanceInfoQuery = new UserInterfanceInfo();
        if (interfanceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfanceInfoQueryRequest, interfanceInfoQuery);
        }
        QueryWrapper<UserInterfanceInfo> queryWrapper = new QueryWrapper<>(interfanceInfoQuery);
        List<UserInterfanceInfo> interfanceInfoList = userInterfanceInfoService.list(queryWrapper);
        return ResultUtils.success(interfanceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param userInterfanceInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<IPage<UserInterfanceInfo>> listPostByPage(@RequestBody UserInterfanceInfoQueryRequest userInterfanceInfoQueryRequest, HttpServletRequest request) {
        if (userInterfanceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfanceInfo userInterfanceInfo = new UserInterfanceInfo();
        BeanUtils.copyProperties(userInterfanceInfoQueryRequest, userInterfanceInfo);
        Long userid = userInterfanceInfo.getUserid();
        Long intrefanceid = userInterfanceInfo.getIntrefanceid();
        Long totalnum = userInterfanceInfo.getTotalnum();
        Long usenum = userInterfanceInfo.getUsenum();
        Integer status = userInterfanceInfo.getStatus();
        long current = userInterfanceInfoQueryRequest.getCurrent();
        long pageSize = userInterfanceInfoQueryRequest.getPageSize();
        // 限制爬虫
        if (pageSize > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        LambdaQueryWrapper<UserInterfanceInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (userid!=null && userid>0){
            queryWrapper.eq(UserInterfanceInfo::getUserid,userid);
        }

        if (intrefanceid!=null && intrefanceid>0){
            queryWrapper.eq(UserInterfanceInfo::getIntrefanceid,intrefanceid);
        }
        if (status != null) {
            queryWrapper.eq(UserInterfanceInfo::getStatus, status);
        }
//        queryWrapper.like(InterfanceInfo::getStatus,status);
        IPage<UserInterfanceInfo> interfanceInfoPage = userInterfanceInfoService.page(new Page<>(current, pageSize), queryWrapper);
        return ResultUtils.success(interfanceInfoPage);
    }
}
